<template>
    <div class="config">
        <div class="page-header">
            <h2>权限分配</h2>
        </div>

        <div class="common-layout">
            <el-container>
                <!-- 左侧角色列表 -->
                <el-aside style="width: 300px;">
                    <el-card style="height: calc(100vh - 160px); overflow-y: auto;">
                        <template #header>
                            <div class="card-header">
                                <span>角色列表</span>
                                <el-button type="primary" @click="refreshRole">刷新</el-button>
                            </div>
                        </template>
                        <!-- 角色列表 -->
                        <ul class="role-list">
                            <li v-for="role in roles" :key="role.id" :class="{ active: selectedRole === role.id }"
                                @click="selectRole(role.id)">
                                {{ role.name }}
                            </li>
                        </ul>
                    </el-card>
                </el-aside>

                <!-- 右侧权限分配详情 -->
                <el-main style="padding: 0px;margin-left: 10px;">
                    <el-card style="height: calc(100vh - 160px); overflow-y: auto;">
                        <template #header>
                            <div class="card-header">
                                <span>菜单列表</span>
                                <div>
                                    <el-button type="primary" @click="save" :disabled="!selectedRole">保存
                                    </el-button>
                                    <el-button type="primary" @click="refreshMenu">刷新</el-button>
                                </div>
                            </div>
                        </template>

                        <el-table ref="multipleTableRef" default-expand-all :data="menus" border style="width: 100%"
                            row-key="id" @selection-change="handleSelectionChange"
                            :tree-props="{ checkStrictly: true }">
                            <el-table-column type="selection" width="55" />
                            <el-table-column prop="title" label="菜单名称" width="200" />
                            <el-table-column label="类型">
                                <template #default="{ row }">
                                    <el-tag :type="row.type === 1
                                        ? 'success'
                                        : row.type === 2
                                            ? 'info'
                                            : 'warning'
                                        ">
                                        {{ row.type === 1 ? '页面' : row.type === 2 ? '菜单' : '按钮' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="description" label="描述" />
                            <el-table-column prop="enable" label="状态" width="100">
                                <template #default="{ row }">
                                    <el-tag :type="row.enable ? 'success' : 'error'">
                                        {{ row.enable ? '启用' : '禁用' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                </el-main>
            </el-container>
        </div>
    </div>
</template>

<script setup>
import { onMounted, ref, inject } from 'vue';
const axios = inject('$axios'); // 从全局属性注入 axios

// 示例角色数据
const roles = ref([]);
const menus = ref([]);
const selectedRole = ref(null);
const selectedMenus = ref([]); // 存储选中菜单的 ID 集合
const multipleTableRef = ref()

// 切换选中角色
const selectRole = async (roleId) => {
    selectedRole.value = roleId;
    // 获取该角色对应的权限信息
    await getRolePermissions(roleId);
};

// 刷新角色列表
const refreshRole = () => {
    getRoles();
    ElMessage.success('刷新角色成功');
};

// 刷新菜单列表
const refreshMenu = async () => {
    await getMenus();
    ElMessage.success('刷新菜单成功');
};

// 获取菜单数据
const getMenus = async () => {
    const result = await axios.get('/Permission/QueryMenusAsync');
    if (result.statusCode == 200 && result.success == true) {
        menus.value = result.response;
    } else {
        ElMessage.error('获取菜单列表失败');
    }
};

// 获取角色数据
const getRoles = async () => {
    const result = await axios.get('/Role/QueryRoleAsync');
    if (result.statusCode === 200 && result.success === true) {
        roles.value = result.response;
    } else {
        ElMessage.error('获取角色列表失败');
    }
};

// 获取角色对应权限
const getRolePermissions = async (roleId) => {
    const result = await axios.get(`/RolePermission/GetRolePermissionsAsync?roleId=${roleId}`);
    if (result.statusCode === 200 && result.success === true) {
        // 根据返回的权限数据，更新选中的菜单
        const permissionIds = result.response;
        selectedMenus.value = permissionIds;
        // 更新菜单选中状态
        updateMenuSelection(selectedMenus.value);
    } else {
        ElMessage.error('获取角色权限失败');
    }
};

const updateMenuSelection = (ids) => {
    // 更新选中状态的函数
    const updateSelection = (menus) => {
        menus.forEach(menu => {
            // 检查当前菜单是否在选中的权限列表中
            const isSelected = ids.includes(menu.id);
            // 更新当前菜单的选中状态
            multipleTableRef.value.toggleRowSelection(menu, isSelected);

            // 只递归处理有子菜单的部分
            if (menu.children && menu.children.length > 0) {
                // 递归对子菜单进行相同操作
                updateSelection(menu.children);
            }
        });
    };

    // 调用更新选中状态的函数
    updateSelection(menus.value);
};


// 监听选中变化
const handleSelectionChange = (val) => {
    selectedMenus.value = val.map(menu => menu.id); // 更新选中的菜单 ID 集合
};

// 保存数据
const save = async () => {
    if (!selectedRole.value) {
        ElMessage.error('请先选择一个角色');
        return;
    }

    try {
        const payload = {
            RoleId: selectedRole.value,
            PermissionIds: selectedMenus.value,
        };
        const result = await axios.post('/RolePermission/AssignPermissionsAsync', payload);
        if (result.statusCode === 200 && result.success === true) {
            ElMessage.success('权限分配成功');
        } else {
            ElMessage.error(result.message || '权限分配失败');
        }
    } catch (error) {
        console.error(error);
        ElMessage.error('请求失败，请稍后重试');
    }
};

// 初始化数据
onMounted(async () => {
    await getMenus();
    setTimeout(() => getRoles(), 100); // 延迟 50ms 获取角色数据
});
</script>

<style scoped>
.el-card {
    height: calc(100vh - 160px);
    overflow: hidden;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header span {
    font-weight: bold;
}

.role-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.role-list li {
    padding: 10px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
    transition: background-color 0.3s ease;
    user-select: none;
}

.role-list li:hover {
    background-color: #f9f9f9;
}

.role-list li.active {
    background-color: #009688;
    color: #fff;
    font-weight: bold;
}
</style>
